library(Matching)

matriculant_matching <- function(var){
  
  var = enquo(var)
  
  df <-
    data_2 %>% 
    filter(abs(forcing_final) < 1, got_job == 1) %>%
    mutate(outcome = !!var) %>%
    filter(!is.na(outcome)) %>%
    dplyr::select(Y = outcome,
                  Tr = matriculant,
                  GENDER,
                  AGE,
                  RELIGION
                  )
  
  Y = df$Y
  Tr = df$Tr
  X = 
    df %>%
    dplyr::select(GENDER, AGE, RELIGION) %>%
    as.matrix()
  
  rr <- Match(Y=Y,Tr=Tr,X=X,M=1)  
  
  c(rr$est, rr$se, (rr$est/rr$se), rr$nobs) %>%
    return()
  
}


java_index_matched <- matriculant_matching(java_index_matriculant_bw_1) %>% append("Javan Preferentialism (Javans)")
non_java_index_matched <- matriculant_matching(non_java_index_matriculant_bw_1) %>% append("Javan Preferentialism (non-Javans)")
regional_index_matched <- matriculant_matching(regional_index_matriculant_bw_1) %>% append("Regional Preferentialism")
religious_index_matched <- matriculant_matching(religious_index_matriculant_bw_1) %>% append("Religious Resentment")
corruption_index_matched <- matriculant_matching(corruption_index_matriculant_bw_1) %>% append("Corruption Perceptions")
natl_index_matched <- matriculant_matching(national_index_matriculant_bw_1) %>% append("National Identification")

rbind(java_index_matched,
      non_java_index_matched,
      regional_index_matched,
      religious_index_matched,
      corruption_index_matched,
      natl_index_matched) %>%
  data.frame() %>%
  mutate(iv = c(rep("Matriculant", 6))) %>%
  set_colnames(c("est", "se", "tstat", "N", "outcome", "iv")) %>%
  dplyr::select(iv, outcome, est, se, tstat, N) %>%
  mutate(est = round(as.numeric(est), 3)) %>%
  mutate(se = round(as.numeric(se), 3)) %>%
  mutate(tstat = round(as.numeric(tstat), 3)) %>%
  kbl(., 
      format = "latex",
      caption = "Matriculant Analysis, Propensity Score Matching", 
      booktabs = T,
      escape = F,
      linesep = "",
      align = "llcccc",
      col.names = c("IV:", "DV:", "Estimate", "SE", "T-Stat", "N")) %>%
  kable_styling() %>% 
  #add_header_above(c(" " = 1, "Testing Effect" = 2, "Service Effect" = 2)) %>%
  #column_spec(column = 1, width = "2in") %>%
  as.character() %>%
  
  str_replace(., "\\\\begin\\{table\\}", "\\\\begin{table}[!htbp]") %>%
  
  cat(., file = "./_4_outputs/tables/table_a4.tex")

